<?php


namespace app\admin\model;


use app\common\Common;
use app\http\Http;
use app\pxs\model\StoreInfo;
use app\sys\model\Dict;
use mysql_xdevapi\Result;
use think\Db;
use think\Exception;
use think\facade\Env;
use think\facade\Log;
use think\Model;

class PushStore extends Model
{
    protected $autoWriteTimestamp = true;
    public static $shopChecked = [
        '0' => [
            'color' => '#ff5722',
            'text' => '未审核',
            'list_show' => false,   //普通列表是否显示 成功案例是特殊列表
            'details_show' => false //详情是否显示
        ],
        '1' => [
            'color' => '#1aa094',
            'text' => '已审核|发布中',
            'list_show' => true,
            'details_show' => true
        ],
        '2' => [
            'color' => '#ffa100',
            'text' => '再审核',
            'list_show' => false,
            'details_show' => true
        ],
        '3' => [
            'color' => '#f93c00',
            'text' => '未通过',
            'list_show' => false,
            'details_show' => false
        ],
        '4' => [
            'color' => '#f93c00',
            'text' => '已完结',
            'list_show' => false,
            'details_show' => false
        ]
    ];

    /**
     * 官网数据
     * @param $data //官网数据
     * @return string
     */
    public static function addUp($data)
    {
        $str = "";

        // 筛选
        foreach ($data as $k => $v) {
//            $key = Dict::getLabel("store_key", $k);
            $rules = PushStoreRule::field("title,key,standard,val")->where("key", $k)->select();
            foreach ($rules as $k1 => $rule){
                if($rule && $k){
                    $res = "";
                    switch ($rule["standard"]) {
                        case "包含":
                            if (stristr($v,$rule["val"])){
                                $res = $rule["title"];
                                $str .= $res.",";
                                PushStoreRule::incNum($res);
                            }
                            break;
                        case "大于":
                            if ((int)$v > $rule["val"]){
                                $res = $rule["title"];
                                $str .= $res.",";
                                PushStoreRule::incNum($res);
                            }
                            break;
                        case "小于":
                            if ((int)$v < $rule["val"]){
                                $res = $rule["title"];
                                $str .= $res.",";
                                PushStoreRule::incNum($res);
                            }
                            break;
                        case "等于":
                            if ((int)$v == $rule["val"]){
                                $res = $rule["title"];
                                $str .= $res.",";
                                PushStoreRule::incNum($res);
                            }
                            break;
                        case "介于":
                            $vs = explode("~",$rule["val"]);
                            if ($vs[0]<= (int)$v && $vs[1] > (int)$v){
                                $res = $rule["title"];
                                $str .= $res.",";
                                PushStoreRule::incNum($res);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }

        }
        return $str;
    }

    public static function addGw($sUrl)
    {
        $url = Env::get("GW.STOREURL");
        $resJ = Http::curlGet($url . "?url=" . $sUrl);
        $res = json_decode($resJ, true);
        if($res["code"] != 200){
            return ["false",$res["msg"]."或数据不存在~"];
        }

        return ["true",$res["data"]["result"]];
    }

    public static function add($url, $staffNo, $staffName, $ac_type = 'add')
    {
        $url = trim($url);
        list($err,$data) = self::addGw($url);
        if($err == "false" || $ac_type == 'get_info'){
            return $data;
        }

        $i = self::addUp($data);

        // 添加记录
        StoreInfo::add($data);

        try {
            Db::startTrans();
            $data["url"] = $url;
            if(isset($data["mobile"])){
                $data["mobile"] = decrypt($data["mobile"],Env::get("MOBILE.KEY"));

            }

            if(isset($data["shop_phone"])){
                $data["shop_phone"] = decrypt($data["shop_phone"],Env::get("MOBILE.KEY"));
            }

            $id = PushStore::where("store_id",$data["id"])->value("id");
            if($id){
                return "该店铺已添加";
            }

            $d = UserPvLog::addLog($data);
            PushStore::create(["url" => $url, "key" => $i, "staff_no" => $staffNo, "staff_name" => $staffName, "store_id" => $data["id"]]);
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            return $exception->getMessage();
        }
        return "";
    }


    public static function del($id)
    {
        PushStore::where("id", $id)->delete();
    }

    public static function det($id)
    {
        return PushStore::where("id", $id)->find();
    }

    public static function list($key, $staffNo)
    {
        $p = PushStore::field("*")->where("store_status","");
        if ($key) {
            $p->where("key", "like", "%$key%");
        }
        if ($staffNo) {
            $p->where("staff_no", $staffNo);
        }
        $c = $p->count();
        $data = $p->order("id desc")->select();
        return listDate($data, $c);
    }

    public static function getStore($id)
    {
        $res = [];
        Db::name('push_store_rule')->where('id', 'in', $id)->select();
        $titleArr = PushStoreRule::where("id", "in", $id)->column("title");

        if ($titleArr) {

            $sql = UserPvLog::group("pxs_id")->buildSql();

            $resSql = PushStore::alias("p")
                ->field("l.id as pv_id,l.pxs_id,p.url")
                ->field("
                l.pxs_id as store_id,
                IFNULL(l.url,'') as store_url,IFNULL(l.title,'') as store_title,IFNULL(l.img,'') as store_img,IFNULL(l.address,'') as store_address,
                IFNULL(l.industry,'') as store_industry,IFNULL(l.cost,'') as store_cost,IFNULL(l.pv,'') as store_pv,IFNULL(l.rent,'') as store_rent,
                IFNUll(l.square,'') as store_square
                ")
                ->leftJoin("{$sql} l", "l.pxs_id = p.store_id");

            foreach ($titleArr as $k => $v) {
                $resSql->whereor("key", "like", "%$v%");
            }
            $res = $resSql->order('p.update_time desc')->where('store_status','')->group("p.store_id")->select();
        }
        return $res;
    }

    public static function upStatus($ids,$status)
    {
        $idArr = explode(",",$ids);

        foreach ($idArr as $key => $id){

            $res = PushStore::where("id",$id)->find();
            if(!$res){
                Log::info("upStatus 修改店铺状态-店铺不存在~");
            }

            PushStore::where("store_id",$id)->update(["store_status"=>$status]);
        }

    }
}